﻿using Brc_PaaS.Bll.Redis;
using Brc_PaaS.Bll.System;
using Brc_PaaS.Common.Entity;
using Brc_PaaS.Common.Model.Basic;
using Brc_PaaS.Core.Redis;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;

namespace Brc_PaaS.Api.Common
{
    /// <summary>
    /// 基础控制器
    /// </summary>
    [ApiController]
    public class RedisBaseController : BaseController
    {

        private readonly IRedis _redis;
        private RedisServerEntity _businessRedisServerEntity = null;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="configuration"></param>
        /// <param name="redis"></param>
        /// <param name="system"></param>
        public RedisBaseController(IConfiguration configuration, IRedis redis,ISystem system) : base(configuration, system)
        {
            _redis = redis;
        }


        /// <summary>
        /// 当前访问平台的业务系统的专属Redis配置
        /// </summary>
        protected RedisServerEntity BusinessRedisServerEntity
        {
            get
            {
                if (_businessRedisServerEntity == null)
                {
                    if (SystemInfo != null)
                    {
                        Ass_Redis model = null;
                        using (IRedisManager redisManager = new RedisManager(RedisServerEntity))
                        {
                            model = redisManager.GetOrFetchFromHash<Ass_Redis>($"RedisDb:{SystemId}", id =>
                            {
                                var result = _redis.GetRedisDb(SystemId);
                                return result.Data;
                            });
                        }
                        if (model != null)
                        {
                            _businessRedisServerEntity = new RedisServerEntity()
                            {
                                ServerAddress = $"{model.Ip}:{model.Port}",
                                InitDB = model.DbNumber,
                                Name = SystemInfo.Name,
                                ConnectTimeout = 60,
                                Password = model.Passwords
                            };
                        }
                    }
                }

                return _businessRedisServerEntity;
            }

        }
    }

}

